﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;

namespace Innovox.NetTools
{
     public class HttpRequest
    {
        const int BUFFER_SIZE = 1024;
        HttpRequestContext context;

        public HttpRequest(string url)
        {
            context = HttpRequestContext.Create(url);
            HttpWebRequest myHttpWebRequest = context.Request;
            myHttpWebRequest.ContentLength = 0;
        }
        
        public void Post(string body)
        {
            try
            {
                context.SetMethod("POST");
                WriteRequestStream(body);
                context.GetResponse();
            }
            catch (Exception e)
            {
                context.SetErrorMessage(e.Message);
                throw new Exception(context.ErrorMessage);
            }
        }

        public void Get()
        {
            try
            {
                context.SetMethod("GET");
                context.GetResponse();
            }
            catch (Exception e)
            {
                context.SetErrorMessage(e.Message);
                throw new Exception(context.ErrorMessage);
            }
        }

        public string ResponseToString()
        {
            return context.RequestDataToString();
        }

        private void WriteRequestStream(string body)
        {
            HttpWebRequest request = context.Request;
            byte[] bodyBuf = BodyToUtf8Array(body);
            request.ContentLength = bodyBuf.Length;
            Stream postStream = request.GetRequestStream();
            postStream.Write(bodyBuf, 0, bodyBuf.Length);
            postStream.Close();
        }

        private byte[] BodyToUtf8Array(string body)
        {
            byte[] utf8Body;
            utf8Body = Encoding.UTF8.GetBytes(body);
            return utf8Body;
        }
    }
}
